//
//  BRAreaViewController.m
//  BrezzeSaaS
//
//  Created by IOS on 2021/9/24.
//  Copyright © 2021 Brezze GWG. All rights reserved.
//

#import "BRAreaViewController.h"
#import "BRAreaTableViewCell.h"
#import "BrezzeAreaModel.h"

@interface BRAreaViewController ()<QMUITableViewDelegate,QMUITableViewDataSource,QMUITextFieldDelegate>
{
    QMUITableView *_myTableView;
    QMUITextField *_searcBar;
}
/**
 *  临时数据源
 */
@property (copy,nonatomic)NSMutableArray *tempDataArray;

@property (nonatomic,strong) NSArray *dataArr;

@property (nonatomic,strong) NSArray *hotArr;
/**
 *  首字母数据源
 */
@property (strong,nonatomic)NSMutableArray *arrayOfCharacters;

@property (nonatomic,assign) BOOL isSearch;

@end

@implementation BRAreaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tempDataArray = [NSMutableArray array];
    self.arrayOfCharacters = [NSMutableArray array];
    [self setUI];
    [self getAreaList];
}

- (BOOL)isSearch {
    return _searcBar.text.length != 0;
}

#pragma mark - request --
- (void)getAreaList {
    
    // 使用静态数据，只保留越南（屏蔽中国和美国）
    NSArray *staticCountries = @[
        @{
            @"name": @"Vietnam",
            @"name_zh": @"越南",
            @"name_vi": @"Việt Nam",
            @"code": @"84",
            @"flag": @"🇻🇳",
            @"abb": @"VN",
            @"hot": @1
        }
        // 屏蔽中国和美国
        // @{
        //     @"name": @"China",
        //     @"name_zh": @"中国",
        //     @"name_vi": @"Trung Quốc",
        //     @"code": @"86",
        //     @"flag": @"🇨🇳",
        //     @"abb": @"CN",
        //     @"hot": @1
        // },
        // @{
        //     @"name": @"United States",
        //     @"name_zh": @"美国",
        //     @"name_vi": @"Hoa Kỳ",
        //     @"code": @"1",
        //     @"flag": @"🇺🇸",
        //     @"abb": @"US",
        //     @"hot": @1
        // }
    ];
    
    // 转换为模型数组
    NSMutableArray *modelArr = [NSMutableArray array];
    for (NSDictionary *dict in staticCountries) {
        BrezzeAreaModel *model = [[BrezzeAreaModel alloc] init];
        model.abb = dict[@"abb"];
        model.code = [dict[@"code"] integerValue];
        model.cn = dict[@"name_zh"];
        model.en = dict[@"name"];
        model.image = dict[@"flag"];
        model.hot = [dict[@"hot"] integerValue];
        [modelArr addObject:model];
    }
    
    // 设置热门国家（全部都是热门）
    self.hotArr = [modelArr copy];
    
    // 按字母分组
    NSMutableArray *LetterResult = [NSMutableArray array];
    NSMutableArray *item = [NSMutableArray array];
    NSString *tempString;

    //拼音分组
    for (BrezzeAreaModel* model in modelArr) {

        NSString *pinyin = nil;
        if ([[BRLanguageManager share] isChinese]) {
            pinyin = [model.cn substringToIndex:1];
        }else {
            pinyin = [model.en substringToIndex:1];
        }
        
        //不同
        if(![tempString isEqualToString:pinyin])
        {
            //分组
            item = [NSMutableArray array];
            [item  addObject:model];
            [LetterResult addObject:item];
            //遍历
            tempString = pinyin;
        }else//相同
        {
            [item  addObject:model];
        }
    }
    [self.arrayOfCharacters removeAllObjects];
    
    for (NSArray *arr in LetterResult) {
        BrezzeAreaModel *model = arr.firstObject;
        
        if ([[BRLanguageManager share] isChinese]) {
            [self.arrayOfCharacters addObject:[model.cn substringToIndex:1]];
        }else {
            [self.arrayOfCharacters addObject:[model.en substringToIndex:1]];
        }
    }
    
    // 插入热门国家到第一位
    [LetterResult insertObject:self.hotArr atIndex:0];
    [self.arrayOfCharacters insertObject:@"*" atIndex:0];
    
    self.tempDataArray = [NSMutableArray arrayWithArray:LetterResult];
    self.dataArr = self.tempDataArray.mutableCopy;
    [self->_myTableView reloadData];
}

#pragma mark - text Delegate --
- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason {
    
    NSLog(@"textFieldDidEndEditing = %@",textField.text);
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    NSLog(@"textFieldShouldBeginEditing = %@",textField.text);
    
    return YES;
}


- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    
    NSLog(@"textFieldShouldEndEditing = %@",textField.text);
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    NSString *searchText = [self searchString:@"" new:textField.text];
    
    [self searchStr:searchText];
    
    [textField endEditing:YES];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    
    [self searchStr:@""];
    
    return YES;
}

- (void)textFieldDidChange:(QMUITextField *)textField {
    
    NSLog(@"textFieldDidChange = [%@]",textField.text);
    
    
    if (textField.text.length != 0) {
        
        [self searchStr:textField.text];
    }
}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    NSString *searchText = [self searchString:textField.text new:string];
    NSString *searchText = [BRTools searchString:textField.text new:string rang:range];
//    NSLog(@"textFieldShouldEndEditing = %@ , string = %@ , searchText = [%@]",textField.text,string,searchText);
    [self searchStr:searchText];
    
    return YES;
}

- (void)searchStr:(NSString *)searchText {
    dispatch_async(dispatch_get_main_queue(), ^{
       
        if ([searchText isEqualToString:@""] || searchText.length == 0) {
            self->_searcBar.text = @"";
            [self.arrayOfCharacters removeAllObjects];
            for (NSArray *arr in self.dataArr) {
                BrezzeAreaModel *model = arr.firstObject;
                if ([[BRLanguageManager share] isChinese]) {
                    [self.arrayOfCharacters addObject:[model.cn substringToIndex:1]];
                }else {
                    [self.arrayOfCharacters addObject:[model.en substringToIndex:1]];
                }
            }
            self.tempDataArray = [self.dataArr mutableCopy];
            [self->_myTableView reloadData];
            
        } else {
            
            [self searchFriends:searchText];
        }
        
    });
}

- (void)searchFriends:(NSString *)inputStr{
    
    if (inputStr.length != 0) {
        
        NSMutableArray *temp = [NSMutableArray array];
        int first = self.hotArr.count != 0 ? 1 : 0;
        for (int i = first; i < self.dataArr.count; i ++) {
            
            NSArray *resultArray = [self.dataArr[i] mutableCopy];
            
            NSMutableArray *tempArray = [NSMutableArray array];
            for (int i = 0; i < resultArray.count; i ++) {
                
                BrezzeAreaModel *model = resultArray[i];

                NSString *codeStr = [NSString stringWithFormat:@"%ld",model.code];
                BOOL hasCode = [codeStr containsString:inputStr];
                BOOL hasEn = [model.en.lowercaseString containsString:inputStr.lowercaseString];
                BOOL hasCn = [model.cn containsString:inputStr];
                if (hasCode || hasEn || hasCn) {
                    if (self.tempDataArray.count != 0) {
                        self.tempDataArray = nil;
                        self.arrayOfCharacters = nil;
                    }
                    [tempArray addObject:model];
                }
                
            }
            if (tempArray.count != 0) {
                [temp addObject:tempArray];
            }
        }
        
        self.tempDataArray = [temp mutableCopy];
        [self.arrayOfCharacters removeAllObjects];
        for (NSArray *arr in self.tempDataArray) {
            BrezzeAreaModel *model = arr.firstObject;
            if ([[BRLanguageManager share] isChinese]) {
                [self.arrayOfCharacters addObject:[model.cn substringToIndex:1]];
            }else {
                [self.arrayOfCharacters addObject:[model.en substringToIndex:1]];
            }
        }
        
    }else{
        self.tempDataArray = [self.dataArr mutableCopy];
        [self.arrayOfCharacters removeAllObjects];
        for (NSArray *arr in self.dataArr) {
            BrezzeAreaModel *model = arr.firstObject;
            if ([[BRLanguageManager share] isChinese]) {
                [self.arrayOfCharacters addObject:[model.cn substringToIndex:1]];
            }else {
                [self.arrayOfCharacters addObject:[model.en substringToIndex:1]];
            }
        }
    }
    
    [_myTableView reloadData];
}

- (NSString *)searchString:(NSString *)old new:(NSString *)newStr {
    
    if (newStr.length != 0) {
        return [NSString stringWithFormat:@"%@%@",old,newStr];
    }
    if (old.length == 0) {
        return @"";
    }
    return [old substringWithRange:NSMakeRange(0, old.length - 1)];
}

#pragma mark - table delegate --
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.tempDataArray.count == 0) return 0;
    NSArray *arr = self.tempDataArray[section];
    
    return arr.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
//    if (self.hotArr.count == 0) return self.tempDataArray.count;
    return self.tempDataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BRAreaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BRAreaTableViewCell"];
    
    BrezzeAreaModel *model = self.tempDataArray[indexPath.section][indexPath.row];
    cell.dto  = model;
    
    UIColor *backC = UIColor.qd_backgroundColor;
    UIColor *titleC = UIColor.qd_mainTextColor;
    UIColor *titleC2 = UIColor.qd_titleTextColor;
    if (self.isLogin) {
        backC = UIColorWhite;
        titleC = UIColorText2;
        titleC2 = UIColorText1;
    }
    cell.backgroundColor = backC;
    cell.contentView.backgroundColor = backC;
    cell.nameL.textColor = titleC;
    cell.numL.textColor = titleC2;
    return cell;
}

- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
    return self.arrayOfCharacters;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
//    if (section > 1)
//        return nil;
    
    UIColor *backC = UIColor.whiteColor;
    UIColor *titleC = kColorMain;
//    if (self.isLogin) {
//        backC = UIColorWhite;
//        titleC = UIColorText1;
//    }

    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 60)];
    header.backgroundColor = backC;
    header.layer.masksToBounds = YES;
    UILabel *labe = [[UILabel alloc] init];
    [header addSubview:labe];
    [labe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(header);
        make.left.equalTo(header).offset(28);
    }];
    labe.font = [UIFont fontH:17];
    labe.textColor = titleC;
    if (self.hotArr.count != 0) {
        labe.text = section == 0 ? Localized(@"login_hot") : Localized(@"login_others");
    }else {
        labe.text = Localized(@"login_others");
        if (section > 0) return nil;
    }


    return header;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (self.hotArr.count != 0) {
        
        UIView *view = [UIView new];
        view.backgroundColor = UIColorWhite;
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section >= 1) return CGFLOAT_MIN;
    if (self.isSearch) {
        return CGFLOAT_MIN;
    }
    if (self.hotArr.count != 0) return 28;
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section > 1) return CGFLOAT_MIN;
    if (self.isSearch) {
        return CGFLOAT_MIN;
    }
    if (self.hotArr.count == 0 && section == 1) {
        return CGFLOAT_MIN;
    }
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BrezzeAreaModel *model = self.tempDataArray[indexPath.section][indexPath.row];
    if (self.selectCodeBlock) {
        
        self.selectCodeBlock(model.code);
    }
    [self pop];
}

#pragma mark - SET UI --
- (void)setUI {
    
    UIColor *backC = UIColor.qd_backgroundColor;
    UIColor *titleC = UIColor.qd_titleTextColor;
    UIColor *lineC = UIColor.qd_lineColor;
    UIColor *titleC2 = UIColor.qd_mainTextColor;
//    if (self.isLogin) {
        backC = UIColorWhite;
        titleC = UIColorText1;
        lineC = UIColorMakeWithRGBA(0, 0, 0, 0.1);
        titleC2 = UIColorText2;
//    }
    
    UIView *top = [self createTop:@""];
    self.view.backgroundColor = backC;
    QMUITextField *searcBar = [[QMUITextField alloc] initWithFrame:CGRectMake(52,KStatusBarHeight + 6, kScreenWidth - 68, 32)];
    searcBar.clearButtonMode = UITextFieldViewModeWhileEditing;
    searcBar.clearButtonPositionAdjustment = UIOffsetMake(-10, 0);
    searcBar.textInsets = UIEdgeInsetsMake(0, 30, 0, 16);
    searcBar.placeholderColor = UIColor.qd_placeholderColor;
    searcBar.textColor =  UIColorText1;
    searcBar.tintColor = kColorMain;
    searcBar.font = [UIFont br_fontM:12];
    searcBar.placeholder = Localized(@"login_search");
    searcBar.autocorrectionType = UITextAutocorrectionTypeNo;
    [searcBar addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [top addSubview:searcBar];
    searcBar.layer.cornerRadius = 16;
    searcBar.returnKeyType = UIReturnKeySearch;
    searcBar.backgroundColor = UIColorText4;
    searcBar.delegate = self;
    UIImageView *secImg = [[UIImageView alloc] initWithImage:UIImageMake(@"login_search")];
    [searcBar addSubview:secImg];
    [secImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.mas_equalTo(12);
        make.centerY.equalTo(searcBar);
        make.left.equalTo(searcBar).offset(10);
    }];
    _searcBar = searcBar;
    
    QMUITableView *tab = [[QMUITableView alloc] initWithFrame:CGRectMake(0, kSafeAreaTopHeight, kScreenWidth, kScreenHeight - kSafeAreaTopHeight) style:UITableViewStyleGrouped];
    tab.backgroundColor = backC;
    tab.delegate = self;
    tab.dataSource = self;
//    [tab setSeparatorInset:UIEdgeInsetsMake(0, 20, 0, 20)];
//    [tab setSeparatorColor:lineC];
    tab.separatorStyle = UITableViewCellSeparatorStyleNone;
    //    tab.rowHeight = 52.;
    tab.estimatedRowHeight = 52;
    tab.sectionIndexColor = titleC2;
    [self.view addSubview:tab];
    [tab registerNib:[UINib nibWithNibName:NSStringFromClass([BRAreaTableViewCell class]) bundle:nil] forCellReuseIdentifier:@"BRAreaTableViewCell"];
    _myTableView = tab;
}

- (UIImage *)navigationBarBackgroundImage {
    return [UIImage qmui_imageWithColor:UIColor.qd_backgroundColor];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
